package org.test.handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.test.dto.JsonMessage;
import org.test.dto.SearchFoodInfoRelDto;
import org.test.pojo.FoodInfo;
import org.test.service.FoodInfoService;

@RestController
public class FoodInfoHandler {
    @Resource
    private FoodInfoService foodInfoService;


    @PostMapping("searchFoodInfoByPage.do")
    public JsonMessage searchFoodInfoByPage(SearchFoodInfoRelDto dto) {
        JsonMessage msg = new JsonMessage();
        // 调用业务
        Long count = foodInfoService.countFoodInfo(dto);
        List<FoodInfo> foodInfoList = null;
        if (count > 0) {
            foodInfoList = foodInfoService.selectByPage(dto);
        }
        // 回应
        msg.setId(0);
        msg.getDatas().put("count", count);
        msg.getDatas().put("foodInfoRelList", foodInfoList);
        return msg;
    }

    @PostMapping("insertFoodInfo.do")
    public JsonMessage insertFoodInfo(FoodInfo foodInfo) {
        JsonMessage msg = new JsonMessage();
        Integer result = foodInfoService.insertFoodInfo(foodInfo);
        // 判断结果
        if (result > 0) {
            msg.setId(0);
            msg.setMsg("上报成功！");
        } else {
            msg.setId(1);
            msg.setMsg("上报失败！");
        }
        return msg;
    }

    @PostMapping("deleteFoodInfoById.do")
    public JsonMessage deleteFoodInfoById(Long id) {
        JsonMessage msg = new JsonMessage();
        Integer result = foodInfoService.deleteFoodInfoById(id);
        // 判断结果
        if (result > 0) {
            msg.setId(0);
            msg.setMsg("删除成功！");
        } else {
            msg.setId(1);
            msg.setMsg("删除失败！");
        }
        return msg;
    }


    @PostMapping("/export.do")
    public void exportStream(HttpServletResponse response, String startCtime, String endCtime, String name, Integer offset, Integer limit) throws UnsupportedEncodingException {
        SearchFoodInfoRelDto dto = new SearchFoodInfoRelDto();
        dto.setStartCtime(startCtime);
        dto.setEndCtime(endCtime);
        dto.setName(name);
        dto.setOffset(offset);
        dto.setLimit(limit);
        Long count = foodInfoService.countFoodInfo(dto);
        List<FoodInfo> foodInfoList = null;
        if (count > 0) {
            foodInfoList = foodInfoService.selectByPage(dto);
        }
        foodInfoList.stream().forEach(x -> {
            if (x.getCardType() == 1) {
                x.setCardTypeTwo("居民身份证");
            } else {
                x.setCardTypeTwo("学生证");
            }

            if (x.getTemperature() == 1) {
                x.setTemperatureTwo("偏低");
            } else if (x.getTemperature() == 2) {
                x.setTemperatureTwo("正常");
            } else if (x.getTemperature() == 3) {
                x.setTemperatureTwo("偏高");
            }
        });

        ExcelWriter writer = ExcelUtil.getBigWriter();

        writer.renameSheet(0, new String("上报数据".getBytes(), "utf-8"));
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        // 设置列名
//      writer.addHeaderAlias("orderId", "orderId");
        writer.addHeaderAlias("name", "姓名");
        writer.addHeaderAlias("phone", "手机号码");
        writer.addHeaderAlias("cardTypeTwo", "证件类型");
        writer.addHeaderAlias("cardCode", "证件号码");
        writer.addHeaderAlias("address", "近期居住地址");
        writer.addHeaderAlias("addressDetail", "详细地址");
        writer.addHeaderAlias("temperatureTwo", "体温情况");
        writer.addHeaderAlias("guangdong", "来粤情况");
        writer.addHeaderAlias("createTime", "上报时间");
        // 设置列宽
        for (int i = 0; i < 6; i++) {
            writer.setColumnWidth(i, 50);
        }
        writer.write(foodInfoList, true);
        String fileName = UUID.randomUUID().toString() + "_AreaData.xlsx";
        ServletOutputStream out = null;
        FileOutputStream fileOutputStream = null;
        String filePath = "";
        try {


            File file = new File("");
            filePath = file.getCanonicalPath() + "/" + fileName;
            fileOutputStream = new FileOutputStream(filePath);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            out = response.getOutputStream();
            writer.flush(out, true);
            //writer.flush(fileOutputStream, true);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writer.close();
            IoUtil.close(fileOutputStream);
            IoUtil.close(out);
            File file = new File(filePath);
            if (file.exists()) {
                boolean delete = file.delete();
            }
        }
    }
}
